<template>
  <div>
    <projectInfo :record="dataSource" v-if="dataSource.length > 0"></projectInfo>
    <el-form ref="postRef" :model="form" :rules="rules" label-width="auto" :label-position="labelPosition">
      <el-row :gutter="24">
        <template v-if="currentRedgerType != '12' && currentRedgerType != '14' && currentRedgerType != '15'">
          <el-col :span="span">
            <el-form-item label="项目编号" prop="projectNo" @click="selectItem">
              <el-input v-model="form.projectNo" placeholder="请选择项目" />
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="span">
          <el-form-item label="收入单位" prop="deptName">
            <el-tree-select v-model="form.deptName" :data="deptOptions" class="el-width" filterable clearable
              :props="{ value: 'label', label: 'label', children: 'children' }" value-key="id" placeholder="请选择收入单位"
              check-strictly @change="getdeptId" />
          </el-form-item>
        </el-col>
        <el-col :span="span">
          <el-form-item label="工作量月份" prop="workloadMonth">
            <el-date-picker v-model="form.workloadMonth" type="month" placeholder="请选择工作量月份" />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="span">
          <el-form-item label="费用明细" prop="subjectName">
            <el-select v-model="form.subjectName" placeholder="请选择费用明细" class="el-width" filterable clearable @change="getSubjectId">
              <el-option v-for="subject in subjectlist" :key="subject.id" :label="subject.subjectName"
                :value="subject.subjectName"></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
        <template v-if="currentRedgerType !== '1' && currentRedgerType !== '16'">
          <el-col :span="span">
            <el-form-item label="内部外部" prop="outerInnerType">
              <el-select v-model="form.outerInnerType" placeholder="请选择内外部" class="el-width" filterable clearable>
                <el-option v-for="dict in orgtype_dept" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <template v-if="currentRedgerType == '1'">
          <el-col :span="span">
            <el-form-item label="经营施工分类" prop="constCategoryName">
              <el-select v-model="form.constCategoryName" placeholder="请选择经营施工分类" class="el-width" filterable clearable
                @change="getdealInTypeId">
                <el-option v-for="item in dealInTypeList" :key="item.id" :label="item.constructionName"
                  :value="item.constructionName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item label="审核" prop="examine">
              <el-select v-model="form.examine" placeholder="是否审核" class="el-width" filterable clearable>
                <el-option v-for="dict in yn" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <template v-if="currentRedgerType == '12' || currentRedgerType == '14' || currentRedgerType == '15'">
          <!-- <template v-if="currentRedgerType == '14' || currentRedgerType == '15'">
            <el-col :span="span">
              <el-form-item label="经营施工分类" prop="constCategoryName">
                <el-select v-model="form.constCategoryName" placeholder="请选择经营施工分类" class="el-width"
                  :disabled="timeUpdete" filterable clearable @change="getdealInTypeId">
                  <el-option v-for="item in dealInTypeList" :key="item.id" :label="item.constructionName"
                    :value="item.constructionName"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </template> -->
          <el-col :span="span">
            <el-form-item label="付款单位" prop="paymentDeptName">
              <el-select v-model="form.paymentDeptName" placeholder="请选择付款单位" class="el-width" filterable clearable
                @change="getpaymentdeptId">
                <el-option v-for="item in PaydeptList" :key="item.id" :label="item.paymentDeptName"
                  :value="item.paymentDeptName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="span">
            <el-form-item label="收入类别" prop="revenueCategory">
              <el-select v-model="form.revenueCategory" placeholder="请选择收入类别" class="el-width" filterable clearable>
                <el-option v-for="dict in revenue_flag" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </template>

      </el-row>
    </el-form>

    <el-dialog title="项目选择" v-model="open" width="900px" append-to-body>
      <!-- 搜索表单 -->
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="项目编号" prop="projectNo">
          <el-input v-model="queryParams.projectNo" placeholder="请输入项目编号" clearable 
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="施工井号" prop="wellNo">
          <el-input v-model="queryParams.wellNo" placeholder="请输入施工井号" clearable style="width: 300px"
            @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker v-model="dates" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间"
            :default-value="[new Date(), new Date()]" style="width: 300px;" @change="getTime" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-form>
      <!-- 数据展示表格-->
      <el-table v-loading="loading" :data="tableData" style="width: 100%" max-height="500" ref="multipleTableRefs"
        @selection-change="handleSelectionChange" @select="handleSelectClick">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="projectNo" label="项目编号" width="150" align="center" />
        <el-table-column prop="wellNo" label="施工井号" width="150" align="center" />
        <el-table-column prop="shortNo" label="施工井号(简)" width="150" align="center" />
        <el-table-column prop="deptThreeName" label="施工队伍" width="150" align="center" />
        <el-table-column prop="constructionName" label="生产施工类型" width="150" align="center" />
        <el-table-column prop="constructionContent" label="施工内容" width="150" align="center" />
        <el-table-column prop="constructionAddress" label="施工地点" width="150" align="center">
          <template #default="scope">
            <dict-tag :options="construction_address" :value="scope.row.constructionAddress" />
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="开工日期" width="150" align="center" />
      </el-table>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getProjectlist" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="js">
import { ref } from 'vue';
import { listManagement, listTwoDept, listConstructionType, listPaydept, getManagement } from '@/api/system/projectManagement';
import { listSubject } from '@/api/cost/subjectList'
import projectInfo from './projectInfo.vue'

const gurrter = ref(24)
const width =ref('120px')
const props = defineProps(['redgerType','span','labelPosition'])
const currentRedgerType = props.redgerType
const span =props.span
const labelPosition = props.labelPosition
// 字典引入
const { proxy } = getCurrentInstance();
const { yn, payment_type, revenue_flag, construction_address, orgtype_dept } = proxy.useDict("yn", "payment_type", "revenue_flag", "construction_address", "orgtype_dept");

// const emit = defineEmits(['change'])
// 表格数据
const tableData = ref([])
const loading = ref(true);
// 数据总数
const total = ref(0)
const open = ref(false)

const dates = ref('')
// 付款单位
const PaydeptList = ref()
//科目列表
const subjectlist = ref()

const queryParams = ref({
  pageNum: 1,
  pageSize: 10
})
const form = ref({})
// 新增表单规则
const rules = ref({
  projectNo: [{ required: true, message: "项目编号不能为空", trigger: "blur" }],
  deptName: [{ required: true, message: "收入单位不能为空", trigger: "blur" }],
  workloadMonth: [{ required: true, message: "工作量月份不能为空", trigger: "blur" }], 

})
// 表格ref
const multipleTableRefs = ref(null)
// 选择列
const selectionChecked = ref([])
const dataSource = ref([])
const selectNo = ref()
//部门下拉树
const deptOptions = ref()
// 获取选中当前行数据
const handleSelectionChange = (checked) => {
  selectionChecked.value = checked
}

const getSubjectOption =()=>{
  listSubject({redgerType:currentRedgerType}).then(res=>{
    subjectlist.value=res.rows
  })
}
const getSubjectId =(Name)=>{
  const list = subjectlist.value.find(item => item.subjectName == Name)
  form.value.subjectId = list.id
}
// 监听项目编号变化
watch(
  () => form.value.projectNo,
  (newValue) => {
    dataSource.value = []
    if (newValue) {
      listManagement({ projectNo: newValue }).then(res => {
        dataSource.value = res.rows
      })
    }
  }, { immediate: true })
// 生产施工分类列表
// const ConstructionTypeList = ref()
// 经营施工分类列表
const dealInTypeList = ref()
/**查询生产施工分类 */
function getConstructionType(typeId) {
  listConstructionType({ constructionFlag: 2 }).then(res => {
    dealInTypeList.value = res.rows
  })
}

/**经营施工分类ID */
function getdealInTypeId(Name) {
  const list = dealInTypeList.value.find(item => item.constructionName == Name)
  form.value.constCategoryId = list.id
}

// 复选框点击触发动作，长度大于1，我们进行取前一个元素，并设置前一个元素的选中状态，那么当前的元素就是可选的一个状态了
const handleSelectClick = (selection) => {
  if (selection.length > 1) {
    const sel_row = selection.shift()
    // toggleRowSelection属性的第二个元素接受的是一个选中状态的布尔值，false不选中，true选中；
    multipleTableRefs.value.toggleRowSelection(sel_row, false)
  }
}
// 项目选择弹框
const selectItem = () => {
  open.value = true
  getProjectlist()
}
/**获取时间 */
const getTime = () => {
  queryParams.value.startDate = dates.value[0]
  queryParams.value.endDate = dates.value[1]
  // getProjectlist()
}
/** 查询部门下拉树结构 */
function getDeptTree() {
  listTwoDept({ parentId: 100 }).then(res => {
    //二级部门
    deptOptions.value = res.data.map(item => ({
      label: item.deptName,
      id: item.deptId,
      children: item.children
    }))
  })
};
/**收入单位ID */
function getdeptId(Name) {
  const list = deptOptions.value.find(item => item.label == Name)
  form.value.deptId = list.id
}

/**查询该项目类型的付款单位 */
function getPaydeptList() {
  listPaydept().then(res => {
    PaydeptList.value = res.data
  })
}
/**付款单位ID */
function getpaymentdeptId(Name) {
  const list = PaydeptList.value.find(item => item.paymentDeptName == Name)
  form.value.paymentDeptId = list.id
}

/**查询项目列表 */
const getProjectlist = () => {
  listManagement(queryParams.value).then(res => {
    tableData.value = res.rows
    total.value = res.total;
    loading.value = false;
  }).catch(error => {
    console.log(error);
  })
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getProjectlist();
}
// 取消
const cancel = () => {
  open.value = false
}
const emit = defineEmits(['innerOuter'])
//确认选择项目
const submitForm = () => {
  dataSource.value = selectionChecked.value
  form.value.projectNo = selectionChecked.value[0].projectNo
  form.value.outerInnerType=selectionChecked.value[0].projectType
  form.value.constCategoryName=selectionChecked.value[0].operateName
  emit('innerOuter',selectionChecked.value[0].projectType)
  open.value = false;
}
//表单验证
async function validateForm() {
  const flag = ref(false)
  await proxy.$refs['postRef'].validate((valid) => {
    flag.value = valid
  })
  return flag.value
}
getConstructionType()
getDeptTree();
getPaydeptList();
getSubjectOption()
defineExpose({ form, validateForm })
</script>
<style scoped>
.el-width{
  width: 500px;
}
</style>